﻿using System;
using System.Collections.Generic;

namespace ProblemsSet
{
    public class Problem_49 : BaseProblem
    {
        public override object GetResult()
        {
            const int cnt = 3;
            const long ex = 1487;

            var val = new HashSet<long>(MathLogic.GetPrimeList(10000, true));
            var exists = new HashSet<long>();
            exists.Add(ex);

            var result = new List<List<long>>();

            foreach (var l in val)
            {
                if (l < 1000) continue;
                if (exists.Contains(l)) continue;
                var rs = new List<string>();
                MathLogic.FormeString(ref rs, "", l.ToString(), int.MaxValue);
                var lst = new List<long>();
                foreach (var r in rs)
                {
                    long q = Convert.ToInt64(r);
                    if (q<l || !val.Contains(q) || exists.Contains(q)) continue;
                    //if (q < l || !val.Contains(q)) continue;
                    lst.Add(q);
                    exists.Add(q);
                }
                if (lst.Count < cnt) continue;
                lst.Sort();
                for (var i = 0; i < lst.Count - 1; i++)
                {
                    for (var j = i + 1; j < lst.Count; j++)
                    {
                        var tmp = new List<long>();
                        tmp.Add(lst[i]);
                        tmp.Add(lst[j]);
                        var d = lst[j] - lst[i];
                        while (lst.Contains(tmp[tmp.Count - 1] + d))
                        {
                            tmp.Add(tmp[tmp.Count - 1] + d);
                        }
                        if (tmp.Count >= cnt) result.Add(tmp);
                    }
                }
            }
            var res = "";
            foreach (var l in result[0])
            {
                res += l.ToString();
            }
            return res;
        }

        public override string Problem
        {
            get
            {
                return @"The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.

What 12-digit number do you form by concatenating the three terms in this sequence?";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return "296962999629";
            }
        }
    }
}
